package com.yinquan.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 
 * @date   2021年5月16日 下午8:12:35
 * @author XiaoHuang
 *
 */
public class ImageBase64 {
	    static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
	    static BASE64Decoder decoder = new sun.misc.BASE64Decoder();

	    //ok
//	    public static void main(String[] args) {
//	        log.info(getImageBinary("C:\\Users\\Administrator\\Desktop\\新平台素材\\光明科技馆.jpg")); // image to base64
//	        base64StringToImage(getImageBinary("C:\\Users\\Administrator\\Desktop\\新平台素材\\光明科技馆.jpg"),"C:\\Users\\Administrator\\Desktop\\新平台素材\\光明科技馆2.jpg"); // base64 to image
//	    }

	    /**
	     * 编码成base64
	     * @param fileInPath 图片路径，例如 d://in.jpg
	     * @return
	     */
	    static String getImageBinary(String fileInPath) {
	        File f = new File(fileInPath);
	        try {
	            BufferedImage bi = ImageIO.read(f);
	            ByteArrayOutputStream baos = new ByteArrayOutputStream();
	            ImageIO.write(bi, "jpg", baos);
	            byte[] bytes = baos.toByteArray();

	            return encoder.encodeBuffer(bytes).trim();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        return null;
	    }

	    /**
	     * base64解码成图片
	     * @param base64String  需要解码的base64字符串
	     * @param fileOutPath   图片存放路径，类似 d://out.jpg
	     */
	    static void base64StringToImage(String base64String,String fileOutPath) {
	        try {
	            byte[] bytes1 = decoder.decodeBuffer(base64String);
	            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
	            BufferedImage bi1 = ImageIO.read(bais);
	            File f1 = new File(fileOutPath);
	            ImageIO.write(bi1, "jpg", f1);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
}
